package com.heima.msg.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.ValueMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Arrays;

@Component
@Slf4j
public class KafkaStreamHelloListener {

    @Bean
    public KStream<String, String> stream(StreamsBuilder streamsBuilder){
        KStream<String, String> stream = streamsBuilder.stream("itcast-topic-input");

        stream.flatMapValues(new ValueMapper<String, Iterable<String>>() {
            @Override
            public Iterable<String> apply(String value) {
                return Arrays.asList(value.split(" "));
            }
        }).groupBy((key,value) -> value)
                .windowedBy(TimeWindows.of(Duration.ofSeconds(5)))
                .count()
                .toStream()
                .map((key, value) -> {
                    System.out.println(key + " : " +value );
                    return new KeyValue<>(key.key(), value.toString());
                })
                .to("itcast-topic-out");

        return stream;
    }
}
